import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'index.dart';
import '../../../common/models/index.dart';
import '../../../common/components/index.dart';

/// 我的发布页面视图
/// 
/// 显示用户发布的活动，支持：
/// - 三个标签（进行中、已结束、我的参与）
/// - 下拉刷新
/// - 活动管理（编辑、删除）
class MyPublishPage extends GetView<MyPublishController> {
  const MyPublishPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF8F9FA),
      appBar: AppBar(
        leading: IconButton(
          onPressed: () => Get.back(),
          icon: const Icon(Icons.arrow_back_ios_new_outlined),
        ),
        title: Text(
          '我的发布',
          style: TextStyle(
            color: const Color(0xFF333333),
            fontSize: 17.sp,
            fontWeight: FontWeight.bold,
          ),
        ),
        backgroundColor: Colors.white,
        elevation: 0,
        centerTitle: true,
        iconTheme: const IconThemeData(color: Color(0xFF333333)),
      ),
      body: Column(
        children: [
          // 子TabBar
          _buildPublishTabBar(),
          
          // 内容区域
          Expanded(
            child: Obx(() {
              // 加载中
              if (controller.isLoadingMyActivities.value) {
                return const Center(
                  child: CircularProgressIndicator(
                    valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFD84545)),
                  ),
                );
              }
              
              // 根据子Tab显示不同内容
              switch (controller.publishTabIndex.value) {
                case 0:
                  return _buildMyOngoingActivities();
                case 1:
                  return _buildMyEndedActivities();
                case 2:
                  return _buildMyParticipatedActivities();
                default:
                  return const SizedBox();
              }
            }),
          ),
        ],
      ),
    );
  }

  /// 构建发布子TabBar
  Widget _buildPublishTabBar() {
    return Container(
      color: const Color(0xFFF8F9FA),
      padding: EdgeInsets.fromLTRB(10.w, 6.h, 10.w, 6.h),
      child: Obx(() {
        final tabs = [
          {'title': '进行中', 'icon': Icons.play_circle_outline, 'color': const Color(0xFF4FC3F7)},
          {'title': '已结束', 'icon': Icons.check_circle_outline, 'color': const Color(0xFF66BB6A)},
          {'title': '我的参与', 'icon': Icons.people_outline, 'color': const Color(0xFFFF9800)},
        ];
        
        return Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(12.r),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withValues(alpha: 0.04),
                blurRadius: 6.r,
                offset: Offset(0, 2.h),
              ),
            ],
          ),
          child: Row(
            children: List.generate(3, (index) {
              final tab = tabs[index];
              final isActive = controller.publishTabIndex.value == index;
              
              return Expanded(
                child: GestureDetector(
                  onTap: () => controller.switchPublishTab(index),
                  child: Container(
                    padding: EdgeInsets.symmetric(vertical: 10.h),
                    decoration: BoxDecoration(
                      gradient: isActive
                          ? const LinearGradient(
                              colors: [Color(0xFFFF6B6B), Color(0xFFD84545)],
                            )
                          : null,
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Icon(
                          tab['icon'] as IconData,
                          size: 20.r,
                          color: isActive ? Colors.white : (tab['color'] as Color),
                        ),
                        SizedBox(height: 4.h),
                        Text(
                          tab['title'] as String,
                          style: TextStyle(
                            fontSize: 12.sp,
                            fontWeight: isActive ? FontWeight.w600 : FontWeight.w500,
                            color: isActive ? Colors.white : const Color(0xFF666666),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              );
            }),
          ),
        );
      }),
    );
  }

  /// 构建进行中的活动
  Widget _buildMyOngoingActivities() {
    return Obx(() {
      if (controller.myOngoingActivities.isEmpty) {
        return _buildEmptyState('暂无进行中的活动', '快去发布活动吧');
      }
      
      return RefreshIndicator(
        color: const Color(0xFFD84545),
        onRefresh: () => controller.loadMyActivities(),
        child: CustomScrollView(
          slivers: [
            SliverPadding(
              padding: EdgeInsets.all(12.r),
              sliver: SliverGrid(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  childAspectRatio: 0.58,  // 🔥 调整宽高比，为操作按钮留出更多空间
                  crossAxisSpacing: 10.w,
                  mainAxisSpacing: 10.h,
                ),
                delegate: SliverChildBuilderDelegate(
                  (context, index) {
                    return _buildMyActivityCard(
                      controller.myOngoingActivities[index],
                      showActions: true,
                    );
                  },
                  childCount: controller.myOngoingActivities.length,
                ),
              ),
            ),
            
            // 底部提示
            SliverToBoxAdapter(
              child: Container(
                height: 50.h,
                color: const Color(0xFFF8F9FA),
                child: Center(
                  child: Text(
                    '共 ${controller.myOngoingActivities.length} 个活动',
                    style: TextStyle(
                      fontSize: 13.sp,
                      color: Colors.grey[400],
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      );
    });
  }

  /// 构建已结束的活动
  Widget _buildMyEndedActivities() {
    return Obx(() {
      if (controller.myEndedActivities.isEmpty) {
        return _buildEmptyState('暂无历史活动', '下拉可刷新');
      }
      
      return RefreshIndicator(
        color: const Color(0xFFD84545),
        onRefresh: () => controller.loadMyActivities(),
        child: CustomScrollView(
          slivers: [
            SliverPadding(
              padding: EdgeInsets.all(12.r),
              sliver: SliverGrid(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  childAspectRatio: 0.72,
                  crossAxisSpacing: 10.w,
                  mainAxisSpacing: 10.h,
                ),
                delegate: SliverChildBuilderDelegate(
                  (context, index) {
                    final activity = controller.myEndedActivities[index];
                    return ActivityCard(
                      activity: activity,
                      onTap: () => controller.viewActivity(activity.activityId),
                    );
                  },
                  childCount: controller.myEndedActivities.length,
                ),
              ),
            ),
            
            // 底部提示
            SliverToBoxAdapter(
              child: Container(
                height: 50.h,
                color: const Color(0xFFF8F9FA),
                child: Center(
                  child: Text(
                    '共 ${controller.myEndedActivities.length} 个活动',
                    style: TextStyle(
                      fontSize: 13.sp,
                      color: Colors.grey[400],
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      );
    });
  }

  /// 构建我的参与活动
  Widget _buildMyParticipatedActivities() {
    return Obx(() {
      if (controller.myParticipatedActivities.isEmpty) {
        return _buildEmptyState('暂无参与的活动', '下拉可刷新');
      }
      
      return RefreshIndicator(
        color: const Color(0xFFD84545),
        onRefresh: () => controller.loadMyActivities(),
        child: CustomScrollView(
          slivers: [
            SliverPadding(
              padding: EdgeInsets.all(12.r),
              sliver: SliverGrid(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  childAspectRatio: 0.72,
                  crossAxisSpacing: 10.w,
                  mainAxisSpacing: 10.h,
                ),
                delegate: SliverChildBuilderDelegate(
                  (context, index) {
                    final activity = controller.myParticipatedActivities[index];
                    return ActivityCard(
                      activity: activity,
                      onTap: () => controller.viewActivity(activity.activityId),
                    );
                  },
                  childCount: controller.myParticipatedActivities.length,
                ),
              ),
            ),
            
            // 底部提示
            SliverToBoxAdapter(
              child: Container(
                height: 50.h,
                color: const Color(0xFFF8F9FA),
                child: Center(
                  child: Text(
                    '共 ${controller.myParticipatedActivities.length} 个活动',
                    style: TextStyle(
                      fontSize: 13.sp,
                      color: Colors.grey[400],
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      );
    });
  }


  /// 构建我的活动卡片（带操作按钮）
  /// 
  /// 尺寸说明：
  /// - 卡片圆角：12.r
  /// - 封面高度：120.h（优化，避免溢出）
  /// - 内边距：8.r
  /// - 标题字体：13.sp
  /// - 描述字体：11.sp
  /// - 标签字体：10.sp
  /// 
  /// 适配说明：
  /// - 使用 Expanded 让内容区自适应高度
  /// - 所有尺寸使用 .w .h .r .sp 适配
  /// - 支持所有屏幕尺寸
  Widget _buildMyActivityCard(ActivityEntity activity, {bool showActions = false}) {
    // 获取封面图
    final coverImage = activity.activityImages?.isNotEmpty == true
        ? activity.activityImages!.first
        : '';
    
    // 获取活动类型
    final activityType = activity.activityType?.isNotEmpty == true
        ? activity.activityType!.first
        : '双方商议';
    
    // 活动类型颜色
    Color tagColor = Colors.red;
    if (activityType == 'AA') {
      tagColor = Colors.orange;
    } else if (activityType == '我买单') {
      tagColor = Colors.green;
    }
    
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.08),
            blurRadius: 8.r,
            offset: Offset(0, 2.h),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 🔥 封面图（可点击查看详情）- 固定高度
          GestureDetector(
            onTap: () => controller.viewActivity(activity.activityId),
            child: Stack(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.vertical(top: Radius.circular(12.r)),
                  child: coverImage.isNotEmpty
                      ? CachedNetworkImage(
                          imageUrl: coverImage,
                          width: double.infinity,
                          height: 120.h,  // 🔥 减小高度，为下方内容留出空间
                          fit: BoxFit.cover,
                          placeholder: (context, url) => Container(
                            height: 120.h,
                            color: Colors.grey[200],
                            child: const Center(child: CircularProgressIndicator()),
                          ),
                          errorWidget: (context, url, error) => Container(
                            height: 120.h,
                            color: Colors.grey[200],
                            child: const Icon(Icons.error),
                          ),
                        )
                      : Container(
                          height: 120.h,
                          color: Colors.grey[200],
                          child: Icon(Icons.image, size: 40.r),
                        ),
                ),
                // 活动类型标签
                Positioned(
                  top: 6.h,
                  right: 6.w,
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 3.h),
                    decoration: BoxDecoration(
                      color: tagColor,
                      borderRadius: BorderRadius.circular(4.r),
                    ),
                    child: Text(
                      activityType,
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 10.sp,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          
          // 🔥 活动信息 - 使用 Expanded 自适应剩余空间
          Expanded(
            child: Padding(
              padding: EdgeInsets.all(8.r),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,  // 🔥 重要：最小化Column高度
                children: [
                  // 活动标题
                  GestureDetector(
                    onTap: () => controller.viewActivity(activity.activityId),
                    child: Text(
                      activity.activityTitle,
                      style: TextStyle(
                        fontSize: 13.sp,  // 🔥 略微减小字体
                        fontWeight: FontWeight.w500,
                        color: Colors.black87,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  
                  SizedBox(height: 3.h),
                  
                  // 活动描述
                  GestureDetector(
                    onTap: () => controller.viewActivity(activity.activityId),
                    child: Text(
                      activity.activityDetails ?? '',
                      style: TextStyle(
                        fontSize: 11.sp,  // 🔥 略微减小字体
                        color: Colors.grey[600],
                        height: 1.2,
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  
                  const Spacer(),
                  
                  // 底部信息
                  Row(
                    children: [
                      // 活动状态
                      Container(
                        padding: EdgeInsets.symmetric(horizontal: 5.w, vertical: 2.h),
                        decoration: BoxDecoration(
                          color: Colors.green.withOpacity(0.1),
                          borderRadius: BorderRadius.circular(3.r),
                        ),
                        child: Text(
                          '进行中',
                          style: TextStyle(
                            fontSize: 9.sp,  // 🔥 减小字体
                            color: Colors.green[700],
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                      const Spacer(),
                      Text(
                        '${activity.currentParticipants ?? 0}/${activity.activityMaxParticipants ?? 10}人',
                        style: TextStyle(
                          fontSize: 10.sp,  // 🔥 减小字体
                          color: Colors.grey[600],
                        ),
                      ),
                    ],
                  ),
                  
                  if (showActions) ...[
                    SizedBox(height: 6.h),
                    Divider(height: 1, thickness: 0.5),
                    SizedBox(height: 5.h),
                    
                    // 🔥 操作按钮 - 紧凑布局
                    Row(
                      children: [
                        Expanded(
                          child: _buildActionButton(
                            icon: Icons.people_outline,
                            label: '管理',
                            color: Colors.blue,
                            onTap: () => controller.manageActivity(activity.activityId),
                          ),
                        ),
                        SizedBox(width: 4.w),
                        Expanded(
                          child: _buildActionButton(
                            icon: Icons.edit_outlined,
                            label: '编辑',
                            color: Colors.orange,
                            onTap: () => controller.editActivity(activity.activityId),
                          ),
                        ),
                        SizedBox(width: 4.w),
                        Expanded(
                          child: _buildActionButton(
                            icon: Icons.delete_outline,
                            label: '删除',
                            color: Colors.red,
                            onTap: () => controller.deleteActivity(activity.activityId),
                          ),
                        ),
                      ],
                    ),
                  ],
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建操作按钮
  /// 
  /// 尺寸说明：
  /// - 按钮圆角：4.r
  /// - 按钮内边距：4.h（垂直）
  /// - 图标大小：12.r
  /// - 字体大小：10.sp
  Widget _buildActionButton({
    required IconData icon,
    required String label,
    required Color color,
    required VoidCallback onTap,
  }) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(4.r),
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 4.h),  // 🔥 减小内边距
        decoration: BoxDecoration(
          color: color.withOpacity(0.1),
          borderRadius: BorderRadius.circular(4.r),  // 🔥 减小圆角
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,  // 🔥 最小化宽度
          children: [
            Icon(icon, size: 12.r, color: color),  // 🔥 减小图标
            SizedBox(width: 3.w),
            Text(
              label,
              style: TextStyle(
                fontSize: 10.sp,  // 🔥 减小字体
                color: color,
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建空状态
  /// 
  /// 尺寸说明（符合 FlutterScreenutil 标准）：
  /// - 图标容器：80.r × 80.r（使用.r保持圆形）
  /// - 图标大小：40.r
  /// - 主标题字体：15.sp
  /// - 副标题字体：13.sp
  /// - 垂直间距：16.h
  Widget _buildEmptyState(String title, String subtitle) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // 空状态图标
          Container(
            width: 80.r,  // 🔥 使用.r保持正方形
            height: 80.r,
            decoration: const BoxDecoration(
              color: Color(0xFFF8F9FA),
              shape: BoxShape.circle,
            ),
            child: Icon(
              Icons.event_note_outlined,
              size: 40.r,
              color: const Color(0xFFBDBDBD),
            ),
          ),
          SizedBox(height: 16.h),
          // 主标题
          Text(
            title,
            style: TextStyle(
              fontSize: 15.sp,
              fontWeight: FontWeight.w600,
              color: const Color(0xFF666666),
            ),
          ),
          SizedBox(height: 6.h),
          // 副标题
          Text(
            subtitle,
            style: TextStyle(
              fontSize: 13.sp,
              color: Colors.grey[400],
            ),
          ),
        ],
      ),
    );
  }
}

